<template>
  <div class="print-dataset-item">
    <el-row>
      <el-form
        class="chart-attribute"
        ref="form"
        :model="formData"
        :rules="rules"
        label-position="top"
        size="default"
        style="height: 100%; width: 100%"
      >
        <el-col :span="24">
          <el-form-item label="显示名称" prop="showName">
            <el-input
              v-model="formData.showName"
              :disabled="!isEdit"
              clearable
              @change="onChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="数据标识" prop="variableName">
            <el-input
              v-model="formData.variableName"
              :disabled="!isEdit"
              clearable
              @change="onChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="数据集" prop="datasetId">
            <el-select
              v-model="formData.datasetId"
              clearable
              filterable
              :disabled="!isEdit"
              placeholder="请选择数据集"
              @change="onDatasetChange"
            >
              <el-option
                v-for="item in datasetList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否迭代">
            <el-switch
              v-model="formData.loop"
              @change="onChange"
              :disabled="
                !isEdit || currentDataset == null || currentDataset.datasetType === DatasetType.API
              "
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          v-if="
            (currentDataset || {}).datasetType === DatasetType.SQL ||
            (currentDataset || {}).datasetType === DatasetType.API
          "
        >
          <MultiItemList
            label="数据集参数"
            :data="formData.datasetFilterParams"
            @add="onSetDatasetParamList()"
            @edit="onSetDatasetParamList()"
            @delete="onRemoveDatasetParam"
            :disabled="!isEdit"
            :prop="{
              label: 'paramName',
              value: 'paramName',
            }"
          >
            <template v-slot="scope">
              <span>{{ scope.data.paramName }}</span>
              <span style="margin: 0px 10px">等于</span>
              <span>{{ scope.data.paramValue }}</span>
            </template>
          </MultiItemList>
        </el-col>
        <el-col :span="24" v-if="(currentDataset || {}).datasetType !== DatasetType.API">
          <MultiItemList
            label="过滤器"
            :data="formData.filterParams"
            :disabled="!isEdit"
            @add="onEditFilter(null)"
            @edit="onEditFilter"
            @delete="onRemoveFilter"
            :prop="{
              label: 'paramName',
              value: 'paramId',
            }"
          >
            <template v-slot="scope">
              <span>{{ (scope.data || {}).paramName }}</span>
              <span style="margin: 0px 10px">{{
                CriteriaFilterType.getValue((scope.data || {}).filterType)
              }}</span>
              <span>
                {{
                  (scope.data || {}).filterValueType === FilterValueKind.INNER_VARIABLE
                    ? CustomDateValueType.getValue((scope.data || {}).paramValue)
                    : (scope.data || {}).paramValue
                }}
              </span>
            </template>
          </MultiItemList>
        </el-col>
        <el-col :span="24" v-if="(currentDataset || {}).datasetType !== DatasetType.API">
          <MultiItemList
            label="排序"
            :data="formData.orderParam"
            :disabled="!isEdit"
            @add="onEditOrder(null)"
            @edit="onEditOrder"
            @delete="onRemoveOrder"
            :prop="{
              label: 'fieldName',
              value: 'fieldName',
            }"
          >
            <template v-slot:right="scope">
              <i
                v-if="scope.data.asc"
                class="el-icon-sort-up"
                style="color: #878d9f; margin-right: 5px; font-size: 12px"
              >
                正序
              </i>
              <i
                v-if="!scope.data.asc"
                class="el-icon-sort-down"
                style="color: #878d9f; margin-right: 5px; font-size: 12px"
              >
                倒序
              </i>
            </template>
          </MultiItemList>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ElMessageBox } from 'element-plus';
import { ANY_OBJECT } from '@/types/generic';
import { Dialog } from '@/components/Dialog';
import {
  CriteriaFilterType,
  DatasetType,
  FilterValueKind,
  CustomDateValueType,
} from '@/common/staticDict/report';
import MultiItemList from '@/components/MultiItemList/index.vue';
import SetReportDatasetParam from '@/pages/report/components/SetReportDatasetParam.vue';
import EditReportColumnFilter from '@/pages/report/components/ReportColumnFilter/editReportColumnFilter.vue';
import EditReportColumnOrder from '@/pages/report/components/ReportColumnOrder/editReportColumnOrder.vue';
import { ThirdProps } from '@/components/thirdParty/types';
import { getFragmentFilterAndOrderColumn } from '@/pages/report/formPrint/components/utils';

const emit = defineEmits(['update:dataset']);

interface IProps extends ThirdProps {
  dataset: ANY_OBJECT;
  isEdit?: boolean;
  printInfo: ANY_OBJECT;
  datasetGroupList?: ANY_OBJECT[];
  datasetList?: ANY_OBJECT[];
  datasetRelationList?: ANY_OBJECT[];
  dictList?: ANY_OBJECT[];
}
const props = withDefaults(defineProps<IProps>(), {
  isEdit: false,
  datasetGroupList: () => {
    return [];
  },
  datasetList: () => {
    return [];
  },
  datasetRelationList: () => {
    return [];
  },
  dictList: () => {
    return [];
  },
});

const form = ref();
const formData = ref<ANY_OBJECT>({
  id: undefined,
  showName: '',
  datasetId: undefined,
  variableName: '',
  loop: false,
  filterParams: [],
  orderParam: [],
  datasetFilterParams: [],
});
const rules = {
  showName: [{ required: true, message: '请输入显示名称', trigger: 'blur' }],
  variableName: [{ required: true, message: '请输入数据标识', trigger: 'blur' }],
  datasetId: [{ required: true, message: '请选择数据集', trigger: 'blur' }],
};

const currentDataset = computed(() => {
  return props.datasetList.find(item => item.id === formData.value.datasetId) || {};
});

const onChange = () => {
  emit('update:dataset', formData.value);
};

watch(
  () => props.dataset,
  val => {
    console.log('props.dataset changed', val);
    if (!val) {
      return;
    }
    formData.value = JSON.parse(JSON.stringify(val));
  },
  {
    immediate: true,
    deep: true,
  },
);

const refreshData = data => {
  if (data.path === 'thirdSetReportDatasetParam' && data.isSuccess) {
    handlerSetDatasetParamList(data.data);
  } else if (data.path === 'thirdEditReportColumnFilter' && data.isSuccess) {
    handlerEditFilter(data.rowData, data.data);
  } else if (data.path === 'thirdEditReportColumnOrder' && data.isSuccess) {
    handlerEditOrder(data.rowData, data.data);
  }
};

const validateForm = async () => {
  try {
    const valid = await form.value.validate();
    return valid;
  } catch (error) {
    console.error('Form validation failed:', error);
    return false;
  }
};

defineExpose({
  refreshData,
  validateForm,
});

const handlerSetDatasetParamList = res => {
  formData.value.datasetFilterParams = (res || []).map(item => {
    return {
      paramName: item.paramName,
      filterValueType: item.filterValueType,
      paramValue: item.paramValue,
    };
  });
  onChange();
};
const handlerEditFilter = (row, res) => {
  if (row == null) {
    // 新增过滤
    formData.value.filterParams.push({
      paramId: res.paramId,
      required: res.required,
      paramName: res.paramName,
      filterType: res.filterType,
      filterValueType: res.filterValueType,
      paramDictId: res.paramDictId,
      paramValue: res.paramValue,
      relationId: res.relationId,
    });
  } else {
    formData.value.filterParams = formData.value.filterParams.map(item => {
      if (item.paramId === res.paramId) {
        return {
          paramId: res.paramId,
          required: res.required,
          paramName: res.paramName,
          filterType: res.filterType,
          filterValueType: res.filterValueType,
          paramDictId: res.paramDictId,
          paramValue: res.paramValue,
          relationId: res.relationId,
        };
      } else {
        return item;
      }
    });
  }
  onChange();
};
const handlerEditOrder = (row, res) => {
  if (row == null) {
    formData.value.orderParam.push({
      ...res,
    });
  } else {
    formData.value.orderParam = formData.value.orderParam.map(item => {
      if (item.fieldName === row.fieldName) {
        return {
          ...res,
        };
      } else {
        return item;
      }
    });
  }
  formData.value.orderParam = formData.value.orderParam.sort((val1, val2) => {
    return val1.showOrder - val2.showOrder;
  });
  onChange();
};
const onDatasetChange = value => {
  formData.value.loop = false;
  formData.value.datasetFilterParams = [];
  formData.value.filterParams = [];
  formData.value.orderParam = [];
  onChange();
};
const onSetDatasetParamList = () => {
  Dialog.show(
    '数据集参数',
    SetReportDatasetParam,
    {
      area: ['900px', '650px'],
    },
    {
      datasetParamList: (currentDataset.value || {}).datasetParamList,
      datasetFilterParams: formData.value.datasetFilterParams,
      formParamList: props.printInfo.paramJson.map(item => {
        return item.variableName;
      }),
      validFilterValueType: [FilterValueKind.PRINT_INPUT_PARAM, FilterValueKind.INPUT_DATA],
      path: 'thirdSetReportDatasetParam',
    },
    {
      width: '900px',
      height: '700px',
      pathName: '/thirdParty/thirdSetReportDatasetParam',
    },
  )
    .then(res => {
      handlerSetDatasetParamList(res);
    })
    .catch(e => {
      // 错误信息
    });
};
const onRemoveDatasetParam = row => {
  ElMessageBox.confirm('是否删除此数据集参数？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(res => {
      formData.value.datasetFilterParams = formData.value.datasetFilterParams.filter(item => {
        return item.paramName !== row.paramName;
      });
      onChange();
    })
    .catch(e => {
      // 错误信息
    });
};
/**
 * 移除排序字段
 */
const onRemoveOrder = row => {
  ElMessageBox.confirm('是否删除此排序？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(res => {
      formData.value.orderParam = formData.value.orderParam.filter(item => {
        return item !== row;
      });
      onChange();
    })
    .catch(e => {
      // 错误信息
    });
};
/**
 * 编辑过滤字段
 */
const onEditFilter = row => {
  console.log('onEditFilter', row, currentDataset.value);
  getFragmentFilterAndOrderColumn(currentDataset.value, null, formData.value.loop)
    .then(res => {
      console.log(res);
      Dialog.show(
        '过滤字段',
        EditReportColumnFilter,
        {
          area: ['600px'],
        },
        {
          rowData: row,
          columnList: res.filterColumnTree,
          formParamList: props.printInfo.paramJson.map(item => {
            return item.variableName;
          }),
          validFilterValueType: [
            FilterValueKind.DICT_DATA,
            FilterValueKind.COLUMN_DATA,
            FilterValueKind.PRINT_INPUT_PARAM,
            FilterValueKind.INNER_VARIABLE,
            FilterValueKind.INPUT_DATA,
          ],
          reportDictList: props.dictList,
          path: 'thirdEditReportColumnFilter',
        },
        {
          width: '600px',
          height: '500px',
          pathName: '/thirdParty/thirdEditReportColumnFilter',
        },
      )
        .then(res => {
          handlerEditFilter(row, res);
        })
        .catch(e => {
          // 错误信息
        });
    })
    .catch(e => {
      // 错误信息
    });
};
/**
 * 移除过滤字段
 */
const onRemoveFilter = row => {
  ElMessageBox.confirm('是否删除此过滤条件？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(res => {
      formData.value.filterParams = formData.value.filterParams.filter(item => {
        return item !== row;
      });
      onChange();
    })
    .catch(e => {
      // 错误信息
    });
};
/**
 * 编辑排序字段
 */
const onEditOrder = row => {
  getFragmentFilterAndOrderColumn(currentDataset.value, null, formData.value.loop)
    .then(res => {
      console.log(res);
      Dialog.show(
        '排序',
        EditReportColumnOrder,
        {
          area: ['600px'],
        },
        {
          rowData: row,
          columnList: res.orderColumnList,
          usedColumnList: (formData.value.orderParam || [])
            .filter(item => {
              return row ? item.fieldName !== row.fieldName : true;
            })
            .map(item => item.fieldName),
          maxOrder: (formData.value.orderParam || []).reduce((maxOrder, item) => {
            return Math.max(maxOrder, item.showOrder || 0);
          }, 0),
          path: 'thirdEditReportColumnOrder',
        },
        {
          width: '600px',
          height: '500px',
          pathName: '/thirdParty/thirdEditReportColumnOrder',
        },
      )
        .then(res => {
          handlerEditOrder(row, res);
        })
        .catch(e => {
          // 错误信息
        });
    })
    .catch(e => {
      // 错误信息
    });
};
</script>

<style scoped>
.readonly-box {
  height: 35px;
  line-height: 35px;
  border-radius: 3px;
  padding: 4px 8px;
}

.readonly-box .delete-btn {
  display: none;
}

.readonly-box:hover {
  background: #f5f7fa;
}

.readonly-box:hover .delete-btn {
  display: inline-block;
}
.print-dataset-item :deep(.el-form-item__label) {
  font-weight: normal !important;
}
</style>
